package cn.school.controller.educational;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.exception.ApiException;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.Subject;
import cn.school.educational.entity.TeachingMaterial;
import cn.school.educational.entity.TeachingMaterialStoreDetils;
import cn.school.educational.service.SubjectService;
import cn.school.educational.service.TeachingMaterialService;
import cn.school.educational.service.TeachingMaterialStoreDetilsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "educational-teachingMaterial => 教材管理")
@RequestMapping("/educational/teachingMaterial")
public class TeachingMaterialController {
    @Autowired
    private TeachingMaterialService teachingMaterialService;
    @Autowired
    private TeachingMaterialStoreDetilsService teachingMaterialStoreDetilsService;
    @Autowired
    private SubjectService subjectService;


    @ApiOperation("获取列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<TeachingMaterial>> list(@RequestParam Map<String, Object> para) {
        int pageNum = Integer.parseInt((String) para.get("pageNum"));
        int pageSize = Integer.parseInt((String) para.get("pageSize"));
        String beginTime = (String) para.get("beginTime");
        String endTime = (String) para.get("endTime");

        Page<TeachingMaterial> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);

        LambdaQueryWrapper<TeachingMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(beginTime)) {
            queryWrapper.ge(TeachingMaterial::getCreateTime, DateUtil.parse(beginTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        }
        if (StrUtil.isNotEmpty(endTime)) {
            queryWrapper.le(TeachingMaterial::getCreateTime, DateUtil.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        }
        queryWrapper.eq(TeachingMaterial::getTenantId, SysUserUtils.getSysUser().getTenantId());

        queryWrapper.orderByDesc(TeachingMaterial::getCreateTime);
        IPage<TeachingMaterial> iPage = this.teachingMaterialService.page(page, queryWrapper);

        // 适用科目显示字段设置
        if (iPage.getRecords() != null && iPage.getRecords().size() != 0) {
            List<Subject> subjectList = this.subjectService.list();
            HashMap<Long, Subject> subjectHashMap = (HashMap<Long, Subject>) subjectList.stream().collect(Collectors.toMap(Subject::getId, obj -> obj));

            for (TeachingMaterial record : iPage.getRecords()) {
                if (subjectHashMap.containsKey(record.getSubjId())) {
                    record.setSubjName(subjectHashMap.get(record.getSubjId()).getSubjName());
                }
            }
        }

        return CommonResult.success(CommonPage.restPage(iPage));
    }


    @ApiOperation("获取单个教材")
    @GetMapping("/info/{id}")
    public CommonResult<TeachingMaterial> getInfoById(@PathVariable Long id) {
        TeachingMaterial subject = this.teachingMaterialService.getById(id);
        return CommonResult.success(subject);
    }


    @ApiOperation("添加教材")
    @PostMapping("/add")
    @Transactional
    public CommonResult<TeachingMaterial> add(@RequestBody TeachingMaterial teachingMaterial) {
        LambdaQueryWrapper<TeachingMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(teachingMaterial.getTemaCode())) {
            queryWrapper.eq(TeachingMaterial::getTemaCode, teachingMaterial.getTemaCode());
            int count = this.teachingMaterialService.count(queryWrapper);
            if (count >= 1) {
                throw new ApiException("教材编号重复，请检查教材编号");
            }
        }
        // 保存教材
        teachingMaterial.setCreateBy(SysUserUtils.getSysUser().getId());
        teachingMaterial.setCreateTime(Calendar.getInstance().getTime());
        teachingMaterial.setModifyTime(Calendar.getInstance().getTime());
        boolean isAddSuccess = this.teachingMaterialService.save(teachingMaterial);

        // 何存sku明细
        TeachingMaterialStoreDetils sku = new TeachingMaterialStoreDetils();
        sku.setTemaCode(teachingMaterial.getTemaCode());
        sku.setTemaName(teachingMaterial.getTemaName());
        sku.setCreateBy(SysUserUtils.getSysUser().getId());
        sku.setCreateTime(Calendar.getInstance().getTime());
        sku.setModifyTime(Calendar.getInstance().getTime());
        sku.setTemaId(teachingMaterial.getId());
        sku.setTmsdType("1"); // 入库
        sku.setTmsdProcNotCount(0);
        sku.setTmsdCount(teachingMaterial.getTemaStoreAmount());
        sku.setTmsdProcAfterCount(teachingMaterial.getTemaStoreAmount());
        boolean isSkuSuccess = this.teachingMaterialStoreDetilsService.save(sku);


        if (isAddSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("更新教材")
    @PutMapping("/update/{id}")
    public CommonResult<Subject> update(@PathVariable Long id, @RequestBody TeachingMaterial teachingMaterial) {
        LambdaQueryWrapper<TeachingMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(TeachingMaterial::getId, teachingMaterial.getId());
        teachingMaterial.setTemaStoreAmount(null);
        if (StrUtil.isNotEmpty(teachingMaterial.getTemaCode())) {
            queryWrapper.eq(TeachingMaterial::getTemaCode, teachingMaterial.getTemaCode());
            int count = this.teachingMaterialService.count(queryWrapper);
            if (count >= 1) {
                throw new ApiException("教材编号重复，请检查教材编号");
            }
        }
        teachingMaterial.setModifyBy(SysUserUtils.getSysUser().getId());
        teachingMaterial.setModifyTime(Calendar.getInstance().getTime());
        boolean isUpdateSuccess = this.teachingMaterialService.updateById(teachingMaterial);
        if (isUpdateSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation("删除教材")
    @DeleteMapping("/deleteByIds/{ids}")
    public CommonResult<TeachingMaterial> add(@PathVariable Long[] ids) {
        List<Long> idsList = Arrays.stream(ids).collect(Collectors.toList());
        List<TeachingMaterial> list = this.teachingMaterialService.listByIds(idsList);
        if (list!=null && list.size()!=0) {
            for (TeachingMaterial teachingMaterial : list) {
                if (teachingMaterial.getTemaStoreAmount() !=0) {
                    throw new ApiException("删除失败！《" +teachingMaterial.getTemaName() + "》库存数量为" + teachingMaterial.getTemaStoreAmount() + "，只允许删除库存为0的教材");
                }
            }
        }
        boolean isDeleteSuccess = this.teachingMaterialService.removeByIds(idsList);
        if (isDeleteSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation("得到所有的科目")
    @GetMapping("/getAllSubject")
    public CommonResult<List<Subject>> getAllSubject() {
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getTenantId, SysUserUtils.getSysUser().getTenantId());
        List<Subject> subjectList =  this.subjectService.list(queryWrapper);
        return CommonResult.success(subjectList);
    }


}
